<template>
  <div>
    <!-- 上传按钮 -->
    <div style="display: flex; justify-content: flex-end; margin-bottom: 16px;">
      <el-button @click="uploadDialogVisible = true">上传简历</el-button>
    </div>

    <!-- 简历表格 -->
    <el-table :data="tableData" style="width: 100%">
      <!-- <el-table-column prop="id" label="简历ID" width="120" /> -->
      <el-table-column prop="userid" label="用户ID" width="120" />
      <el-table-column prop="reid" label="简历岗位" />
      <el-table-column prop="name" label="简历名称" />
      <el-table-column prop="scheme" label="方案" />
      <el-table-column prop="content" label="简历链接" />
      <el-table-column prop="notes" label="备注" />
      <el-table-column prop="todate" label="创建时间" />
      <el-table-column label="查看简历" width="120">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleViewDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination background layout="prev, pager, next" :total="pagination.total" :page-size="pagination.pageSize"
      :current-page="pagination.page" @current-change="handlePageChange" style="margin-top: 16px;" />

    <!-- 上传简历弹窗 -->
    <el-dialog title="上传简历" :visible.sync="uploadDialogVisible" width="500px">
      <el-form :model="uploadForm" label-width="120px">
        <el-form-item label="上传类型">
          <el-radio-group v-model="uploadForm.type">
            <el-radio label="overwrite">覆盖原有版本</el-radio>
            <el-radio label="new">新建简历 ID</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 选择已有简历进行覆盖 -->
        <el-form-item label="选择已有简历" v-if="uploadForm.type === 'overwrite'">
          <el-select v-model="uploadForm.selectedResumeId" placeholder="请选择简历">
            <el-option v-for="item in tableData" :key="item.reid" :label="`${item.name}（方案${item.scheme}）`"
              :value="item.reid" />
          </el-select>
        </el-form-item>

        <!-- 新建简历名称 -->
        <el-form-item label="简历名称" v-if="uploadForm.type === 'new'">
          <el-input v-model="uploadForm.name" placeholder="请输入简历名称" />
        </el-form-item>

        <el-form-item label="上传文件">
          <!-- 修改上传组件部分 -->
          <el-upload class="upload-resume" drag :show-file-list="true" :auto-upload="false"
            :on-change="handleFileChange">
            <!-- 添加on-change事件 -->
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">仅支持 PDF 或 DOC 文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="uploadForm.notes" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResume">确认上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getResumeList, createResume, updateResume } from '@/api/example/resume'
import OSS from 'ali-oss'

export default {
  name: 'ResumeList',
  data() {
    return {
      tableData: [],
      pagination: { page: 1, pageSize: 10, total: 0 },
      uploadDialogVisible: false,
      uploadForm: {
        type: 'overwrite', // 'overwrite' or 'new'
        selectedResumeId: '',
        name: '',
        file: null,
        notes: ''
      },
      ossConfig: {
        region: 'oss-cn-wuhan-lr',
        accessKeyId: 'LTAI5tE1sjS9v6rVPid3HXzr',
        accessKeySecret: 'd3dCLmg0CBQgMX5fbSjZc6qMPWJcMj',
        bucket: 'mangopdf',
      },
    }
  },
  created() {
    this.fetchData();
  },
  computed: {
    // 获取当前用户信息
    currentUser() {
      return this.$store.state.user.userInfo || {};
    }
  },
  methods: {
    fetchData() {
      getResumeList({
        page: this.pagination.page,
        pageSize: this.pagination.pageSize
      }).then(res => {
        const data = res.data || {}
        this.tableData = Array.isArray(data.list) ? data.list : []
        if (data.pagination) {
          this.pagination.total = data.pagination.total || 0
          this.pagination.page = data.pagination.currentPage || 1
          this.pagination.pageSize = data.pagination.pageSize || 10
        }
      })
    },
    handlePageChange(page) {
      this.pagination.page = page
      this.fetchData()
    },
    handleViewDetail(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在下载简历 PDF...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        const resumeId = row.reid
        const downloadUrl = `https://your-domain.com/api/resume/download/${resumeId}`

        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `resume_${resumeId}.pdf`
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } catch (error) {
        console.error('下载简历失败', error)
        this.$message.error('下载简历失败')
      } finally {
        loading.close()
      }
    },
    handleFileChange(file) {
      this.uploadForm.file = file.raw; // 确保获取的是原始文件对象
    },

    async submitResume() {
      // 修改文件验证逻辑
      if (!this.uploadForm.file || !(this.uploadForm.file instanceof File)) {
        this.$message.warning('请上传有效的简历文件');
        return;
      }

      // 检查文件类型
      const fileType = this.uploadForm.file.type;
      const isValidType = fileType === 'application/pdf' ||
        fileType === 'application/msword' ||
        fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';

      if (!isValidType) {
        this.$message.warning('请上传PDF或DOC格式的文件');
        return;
      }

      if (this.uploadForm.type === 'overwrite' && !this.uploadForm.selectedResumeId) {
        this.$message.warning('请选择要覆盖的简历')
        return
      }

      if (this.uploadForm.type === 'new' && !this.uploadForm.name.trim()) {
        this.$message.warning('请输入新建简历名称')
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '正在上传...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        // 将文件转为 Blob 并上传到 OSS
        const blob = new Blob([this.uploadForm.file], { type: this.uploadForm.file.type })
        const ossUrl = await this.uploadToOSS(blob)

        const entity = {
          todate: new Date().toISOString(),
          name: this.uploadForm.name || '简历',
          notes: this.uploadForm.notes || '无',
          scheme: this.uploadForm.scheme || '方案一',
          content: ossUrl,
          inid: localStorage.getItem("id") || 'system',
        };

        const res = await request({
          url: '/api/example/Whu_report',
          method: 'post',
          data: reportData
        });
        // return res;

        if (this.uploadForm.type === 'overwrite') {
          await updateResume(this.uploadForm.selectedResumeId, entity)
        } else {
          // 创建前要生成 id
          // entity.id = RandomUtil.uuId() // 或者由后端生成
          await createResume(entity)
        }

        // const entity = {
        //   name: this.uploadForm.name || '简历',
        //   userid: (this.currentUser && this.currentUser.id) || localStorage.getItem("id") || 'system',
        //   content: ossUrl,
        //   // 简历的链接
        //   notes: this.uploadForm.notes,
        //   todate: new Date().toISOString(),
        //   scheme: '方案一' // 你可以添加更多字段
        // }

        // if (this.uploadForm.type === 'overwrite') {
        //   await updateResume(this.uploadForm.selectedResumeId, entity)
        // } else {
        //   // 创建前要生成 id
        //   // entity.id = RandomUtil.uuId() // 或者由后端生成
        //   await createResume(entity)
        // }

        // this.$message.success('上传成功！')
        // this.uploadDialogVisible = false
        // this.fetchData()
      } catch (err) {
        console.error('上传失败：', err)
        this.$message.error('上传失败，请稍后重试')
      } finally {
        loading.close()
      }
    },
    async uploadToOSS(blob) {
      const client = new OSS(this.ossConfig)

      // 生成唯一文件名
      const fileName = `interview-reports/${this.currentUser.id || 'anonymous'}/${Date.now()}.pdf`

      const result = await client.put(fileName, blob, {
        headers: {
          'Content-Type': this.uploadForm.file.type,
          'Content-Disposition': `inline`
        }
      })
      console.log('上传成功:', result)
      return result.url
    },
    // 保存分析报告到后端
    async saveAnalysisReport(pdfUrl) {
      const reportData = {
        date: new Date().toISOString(),
        inid: localStorage.getItem("id") || 'system',
        analysis: pdfUrl  // 将PDF URL保存到analysis字段
      };

      try {
        const res = await request({
          url: '/api/example/Whu_report',
          method: 'post',
          data: reportData
        });
        return res;
      } catch (error) {
        console.error('保存报告失败:', error);
        throw error;
      }
    },
  }
}
</script>

<style scoped>
.upload-resume {
  width: 100%;
}
</style>
